package com.tanquandan.askbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanquandan.askbackend.dao.ChatMapper;
import com.tanquandan.askbackend.dao.CourseMapper;
import com.tanquandan.askbackend.dao.KeywordMapper;
import com.tanquandan.askbackend.dto.R;
import com.tanquandan.askbackend.entity.Chat;
import com.tanquandan.askbackend.entity.Course;
import com.tanquandan.askbackend.entity.Keyword;
import com.tanquandan.askbackend.service.IChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatService extends ServiceImpl<ChatMapper, Chat> implements IChatService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private KeywordMapper keywordMapper;


    @Override
    public R<Chat> sendMessage(Long userId,String question) {
        // 1. 调用接口得到返回
        String answer = "功能还没开发完成...";
        // 2. 新增用户和相关课程的联系度

        // 2.1 获取分词列表
        List<String> keywords = Arrays.asList("数据库","图像识别","自然语言","数理逻辑");
        keywords.forEach(name -> {
            Keyword keyword = keywordMapper.selectOne(new QueryWrapper<Keyword>().eq("keyword_name", name));
            // 2.2 查找关键词与课程的匹配
            List<Long> courseIds = courseMapper.listCourseByKeyword(keyword.getId()).stream().map(Course::getId).collect(Collectors.toList());
            // 2.3 增加用户和相关课程的联系度
            for (Long courseId : courseIds) {
                Integer count = courseMapper.countCourse2User(courseId, userId);
                if(count == 0){
                    courseMapper.saveCourse2User(courseId,userId);
                }else{
                    courseMapper.updateCourse2User(courseId,userId);
                }
            }
        });

        // 3. 封装成question对象
        Chat chat = new Chat();
        chat.setUserId(userId);
        chat.setQuestion(question);
        chat.setAnswer(answer);
        long timestamp = new Date().getTime();
        chat.setTimestamp(new Timestamp(timestamp));
        chat.setCreateBy(userId);
        chat.setCreateTime(LocalDateTime.now());

        // 4. 存储
        save(chat);

        // 4. 返回
        return R.success(chat);
    }
}
